<?php

namespace app\api\model;

use app\common\enums\StatusEnum;

class Message extends \app\common\model\Message
{
    /**
     * 系统消息列表
     * @param $oauthId
     * @param $page
     * @param $size
     * @return array
     * @throws \think\Exception\DbException
     */
    public static function getList($oauthId, $page, $size)
    {
        $offset = ($page - 1) * $size;
        $sql = static::where(['status' => StatusEnum::ENABLED]);

        $model = $sql->field('id, title, create_time AS createTime')
            ->order(['sort_num' => 'desc', 'create_time' => 'desc'])
            ->limit($offset, $size)
            ->select()
            ->toArray();

        $read = MessageRead::getList($oauthId);
        foreach ($model as $key => $value) {
            $model[$key]['createTime'] = get_datetime($value['createTime']);
            $model[$key]['isRead'] = isset($read[$value['id']]) ? 1 : 0;
        }
        return [
            'list' => $model,
            'count' => $sql->count(),
        ];
    }

    /**
     * 常见问题列表详情
     * @param $oauthId
     * @param $messageId
     * @return array|\PDOStatement|string|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getOne($oauthId, $messageId)
    {
        $model = static::field('id, title, content,create_time')
            ->where(['id' => $messageId, 'status' => StatusEnum::ENABLED])
            ->find();
        if ($model) {
            // 查看是否已读
            $read = MessageRead::getOne($oauthId, $messageId);
            // 更新为已读状态
            if (empty($read)) {
                MessageRead::addOne($oauthId, $messageId);
            }
        }
        return $model ? $model : [];
    }

    /**
     * 获取我的未读系统消息数量
     * @param $oauthId
     * @return float|string
     */
    public static function unreadCount($oauthId)
    {
        $read = MessageRead::getList($oauthId);
        $readIds = array_keys($read);
        $sql = static::where(['status' => StatusEnum::ENABLED]);
        if ($readIds) {
            $sql->where('id', 'not in', $readIds);
        }
        return $sql->count();
    }
}